package main

import (
	"fmt"
	// "strings"
    "os"
	"io"
	"errors"
    shell "github.com/ipfs/go-ipfs-api"
)


func upload(path string) (string, error){
	f, err := os.Open(path)
    if err != nil {
        panic(err)
    }
    defer f.Close()
    var reader io.Reader = f 
	sh := shell.NewShell("localhost:5001")
	cid, err := sh.Add(reader)
	return cid, err
}

func download(cid string, path string) () {
	sh := shell.NewShell("localhost:5001")
	rc, err := sh.Cat(cid) 
	if err != nil {
		fmt.Println("sdf")
		panic(err)
	}
	if path == "" {
		path = "./.cache/" + cid
	}
	file, err := os.Create(path)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	_, err = io.Copy(file, rc)
	if err != nil {
		panic(err)
	}
	fmt.Println(path)
}

func upload_folder(dir string) (string, error) {
	sh := shell.NewShell("localhost:5001")
	if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
		// path/to/whatever does not exist
		fmt.Println("Dir does not eixst")
	}
	cid, err := sh.AddDir(dir)
	return cid, err
}

func download_folder(cid, outdir string) error {
	sh := shell.NewShell("localhost:5001")
	err := sh.Get(cid, outdir)
	return err
}

func main() {
	// Where your local node is running on localhost:5001
	// cid, err := upload("/mnt/c/Users/isudfv/Pictures/wallhaven-y8vlyk.jpg")
	// if err != nil {
    //     fmt.Fprintf(os.Stderr, "error: %s", err)
    //     os.Exit(1)
	// }
    // fmt.Printf("added %s\n", cid)
	// download(cid, "")

	cid, err := upload_folder("/mnt/c/Users/isudfv/Desktop/test")
	download_folder(cid, "./.cache/")
	if err != nil {
		panic(err)
	}
}